<!-- 角色列表 -->
<template>
  <div>
    <div class="row head">
      <q-separator vertical size="3px" class="leftLine bg-primary" />
      <span class="q-ml-md name">角色列表</span>
    </div>
    <div style="height: 750px;" class="bg-white q-pa-md">
      <div v-if="isShowCompany.isShowPre" class="q-mb-md">
        <span class="q-mr-sm">公司</span>
        <q-select
          outlined
          dense
          options-dense
          v-model="company"
          :options="companys"
          class="inline-block"
          style="width: 180px;"
          @update:model-value="changeCompany"
        />
      </div>
      <div class="q-mb-md">
        <span class="q-mr-sm">过滤</span>
        <q-input
          outlined
          v-model="filterRole"
          class="inline-block"
          style="width: 180px;"
          dense
          @update:model-value="handlerRoleFilter(filterRole)"
        />
      </div>
      <div class="q-mb-md">
        <span class="q-mr-sm">操作</span>
        <q-btn
          dense
          unelevated
          color="primary"
          padding="4px 10px"
          label="新增"
          class="borderRadius q-mr-md"
          @click="openDialogCreate"
        />
        <q-btn
          dense
          unelevated
          color="primary"
          padding="4px 10px"
          label="编辑"
          class="borderRadius q-mr-md"
          @click="handlerUpdateRole"
        />
        <q-btn
          dense
          unelevated
          color="primary"
          padding="4px 10px"
          label="删除"
          class="borderRadius"
          @click="isShowDelete = true"
        />
      </div>
      <div class="q-mb-md main-roles">
        <div v-for="role in textRoles" :key="role.id" :class="{'active': isRow === role.id}" class="q-pl-sm">
          <q-input
            v-model="role.name"
            dense
            borderless
            @focus="handlerFocus(role)"
            @update:model-value="handlerRole(role)"
          />
        </div>
      </div>
    </div>
    <q-dialog v-model="isAddOrUpdate" persistent @mousedown="dialogDrag($event, 1)" @mousemove="dragIcon($event)">
        <q-card class="card-style">
          <!-- 对话框的头部 -->
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">添加角色</div>
          <q-space />
          <q-btn icon="close" flat round dense @click="isAddOrUpdate = fasle"></q-btn>
        </q-card-section>
          <!-- 对话框的主体-->
        <q-card-section>
          <q-form ref="assetForm" class=" dialog-form-container">
            <ul>
              <li>
                <span>
                  角色名称
                </span>
                <span>
                  <q-input
                    outlined
                    dense
                    v-model="creatUpdateQuery.name"
                  />
                </span>
              </li>
            </ul>
          </q-form>
        </q-card-section>
          <!-- 对话框的底部 -->
        <q-card-actions align="right">
          <q-btn unelevated label="取消" type="reset" style="color: #686868;" outline @click="isAddOrUpdate = fasle" />
          <q-btn outline label="确定" type="submit" color="primary" @click="handlerUpdateSensor()" />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <DeleteDialog :isShowDelete="isShowDelete" :tipInfo="'确定删除吗？'" @closeDeleteDialog="closeDeleteDialog" @confirmDelete="confirmDelete" />
  </div>
</template>

<script>
import { gainCompanyList, gainRolesList, addRolesList, updateRolesList, deleteRolesList } from 'src/api/permission'
import DeleteDialog from 'src/components/deleteDialog/index'
import drag from 'src/components/mixins/drag.js'

export default {
  mixins: [drag],
  props: {
    isShowCompany: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data () {
    return {
      company: '',
      companys: [],
      filterRole: '',
      textRoles: [],
      isAddOrUpdate: false,
      creatUpdateQuery: {
        name: ''
      },
      isShowDelete: false,
      isRow: false
    };
  },

  components: {
    DeleteDialog
  },

  computed: {},
  watch: {
    isShowCompany: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val && val.isShowPre) {
          this.getAllCompany()
        } else {
          this.company = {}
          this.setAllRoles()
        }
      }
    }
  },

  mounted() {},

  methods: {
    /**
     * 切换不同的公司
     */
    changeCompany(val) {
      if (!val || !val.id) return
      this.company = Object.assign({}, val)
      this.setAllRoles()
    },
    /**
     * 获取所有的公司
     */
    getAllCompany() {
      this.companys = []
      this.company = {}
      gainCompanyList({ all: 'True' }).then(res => {
        const { status, data } = res
        if (status === 200) {
          if (data && data.length > 0) {
            data.forEach(element => {
              const { id, name, addr, img, short_name, title_name, create_time } = element
              this.companys.push({
                value: name,
                label: name,
                id,
                name,
                addr,
                img,
                short_name,
                title_name,
                create_time
              })
            })
            this.company = Object.assign({}, this.companys[0])
          }
        }
      }).then(_ => {
        this.setAllRoles()
      })
    },
    /**
     * 获取所有的角色
     */
    setAllRoles() {
      let query = {}
      if (this.company && this.company.id) query.company_id = this.company.id
      gainRolesList(query).then(res => {
        const { status, data } = res
        if (status === 200) {
          if (data) {
            this.textRoles = data.concat([])
            this.copyRoles = data.concat([])
          }
        }
        this.isRow = this.textRoles.length > 0?this.textRoles[0].id:-1
        this.$store.commit('permission/SET_ROLE_ID', this.isRow)
      })
    },
    // 打开添加的弹框
    openDialogCreate() {
      this.isAddOrUpdate = true
      this.creatUpdateQuery = {
        name: ''
      }
    },
    // 确定添加新的角色
    handlerUpdateSensor() {
      const _query = {}
      _query.name = this.creatUpdateQuery.name
      _query.company_id = this.company.id
      addRolesList(_query).then(res => {
        const { status, data } = res
        this.isAddOrUpdate = false
        if (status === 200) {
          this.setAllRoles()
          this.$q.notify({
            message: '增加成功！',
            type: 'positive',
            position: 'top'
          })
        }
      })
    },
    // 修改文字
    handlerRole(val){
      if (!val || !val.name) return
      this.creatUpdateQuery = val
    },
    // 确定编辑角色名称
    handlerUpdateRole() {
      if (!this.creatUpdateQuery.id) {
        this.$q.notify({
          message: '请确定该角色是否需要编辑',
          type: 'warning',
          position: 'top'
        })
        return
      }
      const _query = {}
      _query.name = this.creatUpdateQuery.name
      _query.company_id = this.company.id
      updateRolesList(this.creatUpdateQuery.id, _query).then(res => {
        const { status, data } = res
        if (status === 200) {
          this.setAllRoles()
          this.$q.notify({
            message: '修改成功！',
            type: 'positive',
            position: 'top'
          })
        }
      })
    },
    // 获取当前需要操作的角色
    handlerFocus(role) {
      if (!role) return
      this.isRow = role.id
      this.deleteRole = role
      this.$store.commit('permission/SET_ROLE_ID', role.id)
    },
    /**
     * 确定删除
     */
    confirmDelete() {
      if (!this.deleteRole || !this.deleteRole.id) {
        this.$q.notify({
          type: 'warning',
          position: 'top',
          message: 'ID不存在！'
        })
        return
      }
      deleteRolesList(this.deleteRole.id).then(res => {
        const {status, msg} = res
        if (status === 200) {
          this.isShowDelete = false
          this.setAllRoles()
          this.$q.notify({
            type: 'positive',
            position: 'top',
            message: `删除成功！`
          })
        } else {
          this.$q.notify({
            type: 'positive',
            position: 'top',
            message: msg
          })
        }
      })
    },
    /**
     * 关闭删除提示框
     */
    closeDeleteDialog() {
      this.isShowDelete = false
    },
    /**
     * 过滤角色
     */
    handlerRoleFilter(val) {
      // 判断输入是否为中文
      let re=/[^\u4E00-\u9FA5]/
      if (re.test(val)) return
      if (!val) {
        this.textRoles = this.copyRoles.concat([])
        if (this.textRoles && this.textRoles.length > 0) {
          this.isRow = this.textRoles[0].id
          this.$store.commit('permission/SET_ROLE_ID', this.isRow)
        }
        return
      }
      this.textRoles = this.textRoles.filter(role => {
        return role.name.indexOf(val) >= 0
      })
      if (this.textRoles && this.textRoles.length > 0) {
        this.isRow = this.textRoles[0].id
        this.$store.commit('permission/SET_ROLE_ID', this.isRow)
      }
    }
  }
}

</script>
<style lang='scss' scoped>
// 弹出的对话框样式
.dialog-form-container {
  ul {
    li {
      height: 42px;
      line-height: 42px;
      white-space: nowrap;
      margin-bottom: 30px;
      >span {
        &:first-child {
          display: inline-block;
          width: 100px;
          margin-right: 5px;
        }
        &:last-child {
          display: inline-block;
          width: 200px;
          >.q-input {
            width: 200px;
          }
        }
      }
    }
  }
}
::v-deep(.main-roles) {
  border: 1px solid #ccc;
  border-radius: 10px;
  height: 520px;
  overflow: auto;
  padding: 10px;
  .q-field--dense .q-field__control, .q-field--dense .q-field__marginal {
    height: 30px;
  }
}

.active {
  background-color: rgba(0,0,0,0.06) !important;
  border-radius: 3px;
}
</style>
